<?php
class Dispatcher {
	private $_controller = null;
	private $_action = null;
	private $_baseurl = null;

	function __construct() {
	}

	function dispatch() {
		$controllerName = $this->getControllerName();
		try {
			$controller = new $controllerName();
		} catch (Exception $e) {
			throw (new Exception('Class not found: '. $controllerName));
		}
		$action = $this->_action;
		if(strlen($action) == 0) $action = $controller->getDefaultAction();

		if(!method_exists($controller, $action)) throw (new Exception('Action method not found: '. $controllerName. '->'. $action));

		if(!$action) $action = $controller->getDefaultAction();

		$form = $controller->getInstanceForm();
		$form->set('baseurl', $this->_baseurl);

		$controller->preDispatch();
		$controller->$action();
		$controller->postDispatch();
	}

	function setController($controller) {
		$this->_controller = $controller;
	}

	function setAction($action) {
		$this->_action = $action;
	}

	function getController() {
		return $this->_controller;
	}

	function getAction() {
		return $this->_action;
	}

	function getControllerName() {
		$controller = strtolower($this->_controller);
		$controllerName = ucfirst($controller).'Controller';
		if(!file_exists(ROOT . 'app/controller/' .$controllerName. '.php')) throw (new Exception('File not found: '. $controllerName));

		require_once  ROOT . 'app/controller/' .$controllerName. '.php';
		return $controllerName;
	}

	function getBaseUrl() {
		return $this->_base_url;
	}

	function setBaseUrl($baseUrl) {
		$this->_baseurl = $baseUrl;
	}
}